package com.jinyu.jyly.ui.home;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.loader.ImageLoader;
import com.jinyu.jyly.R;
import com.jinyu.jyly.base.BaseFragment;
import com.jinyu.jyly.bean.AllInfoBean;
import com.jinyu.jyly.bean.GongGaoInfo;
import com.jinyu.jyly.ui.home.articledetail.ArticleDetailActivity;
import com.jinyu.jyly.utils.AES;
import com.jinyu.jyly.view.tv.ITextBannerItemClickListener;
import com.jinyu.jyly.view.tv.TextBannerView;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 首页
 */
public class    HomeFragment extends BaseFragment<HomePresenter> implements HomeContract.View, ViewPager.OnPageChangeListener {

    @BindView(R.id.fake_status_bar)
    View fakeStatusBar;
    @BindView(R.id.banner)
    Banner banner;
    @BindView(R.id.tv_text_roll)
    TextBannerView tvTextRoll;
    @BindView(R.id.iv_one)
    ImageView ivOne;
    @BindView(R.id.iv_two)
    ImageView ivTwo;
    @BindView(R.id.viewpager)
    ViewPager viewpager;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout mRefreshLayout;
    private HomePresenter presenter;

    @Override
    protected View initView(ViewGroup container) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.fragment_home, container, false);
        return view;
    }

    @Override
    protected void loadData() {
        initViewpager();
        initData();

        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                initData();
            }
        });
    }

    private void initData() {
        try {
            //获取公告
            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("cid", 36);
//            jsonObject1.put("tui", 1);
            String param = AES.encryptToHexString(jsonObject1.toString());
            mPresenter.getSiteArtile(param);
        } catch (JSONException e) {
            e.printStackTrace();
        }


        try {
            //获取banner
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("cid", 37); //37
            String param = AES.encryptToHexString(jsonObject.toString());
            mPresenter.onSiteAd(param);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public HomePresenter getPresenter() {
        if (presenter == null) {
            presenter = new HomePresenter(getActivity(), this);
        }
        return presenter;
    }

    private void initViewpager() {
        MyPagerAdapter myPagerAdapter = new MyPagerAdapter(getChildFragmentManager());
        viewpager.setOffscreenPageLimit(2);
        viewpager.setAdapter(myPagerAdapter);
        viewpager.addOnPageChangeListener(this);
    }

    @OnClick({R.id.iv_one, R.id.iv_two})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_one:
                viewpager.setCurrentItem(0);
                ivOne.setImageResource(R.mipmap.icon_word_news);
                ivTwo.setImageResource(R.mipmap.icon_word_question_normal);
                break;
            case R.id.iv_two:
                viewpager.setCurrentItem(1);
                ivOne.setImageResource(R.mipmap.icon_word_news_normal);
                ivTwo.setImageResource(R.mipmap.icon_word_question);
                break;
            default:
                break;
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        switch (position) {
            case 0:
                ivOne.setImageResource(R.mipmap.icon_word_news);
                ivTwo.setImageResource(R.mipmap.icon_word_question_normal);
                break;
            case 1:
                ivOne.setImageResource(R.mipmap.icon_word_news_normal);
                ivTwo.setImageResource(R.mipmap.icon_word_question);
                break;
            default:
                break;
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    public void onFailer(Throwable throwable) {
        mRefreshLayout.finishLoadMore();
        mRefreshLayout.finishRefresh();
    }

    @Override
    public void onSiteAd(AllInfoBean info) {
        mRefreshLayout.finishLoadMore();
        mRefreshLayout.finishRefresh();
        switch (info.getStatus()) {
            case 200:
                try {
                    String infodata = AES.decrypt(info.getData());
                    Gson gson = new Gson();
                    Type listType = new TypeToken<ArrayList<String>>() {
                    }.getType();
                    List<String> mList = gson.fromJson(infodata, listType);
                    setBanner(mList);

                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case 422:
                showToast(info.getMsg());
                break;
            default:
                break;
        }
    }

    /**
     * 设置banner
     * @param mList
     */
    private void setBanner(List<String> mList) {
        //设置内置样式，共有六种可以点入方法内逐一体验使用。
        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR); //CIRCLE_INDICATOR
        //设置图片加载器，图片加载器在下方
        banner.setImageLoader(new MyLoader());
        //设置图片网址或地址的集合
        banner.setImages(mList);
        //设置轮播图的标题集合
        banner.setBannerTitles(mList);
        //设置轮播的动画效果，内含多种特效，可点入方法内查找后内逐一体验
        banner.setBannerAnimation(Transformer.Accordion);//Default  //Accordion
        //设置轮播间隔时间
        banner.setDelayTime(3000);
        //设置是否为自动轮播，默认是“是”。
        banner.isAutoPlay(true);
        //设置指示器的位置，小点点，左中右。
        banner.setIndicatorGravity(BannerConfig.CENTER) //CENTER
                //以上内容都可写成链式布局，这是轮播图的监听。比较重要。方法在下面。
//                          .setOnBannerListener(this)
                //必须最后调用的方法，启动轮播图。
                .start();
    }

    //自定义的图片加载器
    private class MyLoader extends ImageLoader {
        @Override
        public void displayImage(Context context, Object path, ImageView imageView) {
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            RequestOptions options = new RequestOptions();
            options.error(R.mipmap.space_list);
            Glide.with(context).load(path)
                    .apply(options)
                    .into(imageView);
        }
    }

    /**
     * 获取公告
     * @param infoBean
     */
    @Override
    public void onSiteGongGaoArticle(AllInfoBean infoBean) {
        mRefreshLayout.finishLoadMore();
        mRefreshLayout.finishRefresh();
        switch (infoBean.getStatus()) {
            case 200:
                String beanData = infoBean.getData();
                String result = null;
                try {
                    result = AES.decrypt(beanData);
                    Gson gson = new Gson();

//                    List<GongGaoInfo> mGongGaoList = new ArrayList<>();
//                    GongGaoInfo gongGaoInfo = gson.fromJson(result, GongGaoInfo.class);
//                    mGongGaoList.add(gongGaoInfo);
                    Type listType = new TypeToken<ArrayList<GongGaoInfo>>() {
                    }.getType();
                    List<GongGaoInfo> mGongGaoList = gson.fromJson(result, listType);
                    //平台通告
                    if (mGongGaoList.size() > 0) {
                        //设置文字banner滚动轮播图数据
                        tvTextRoll.setDatas(mGongGaoList);
                        //启动轮播图
                        tvTextRoll.startViewAnimator();
                        //文字轮播图没有点击事件注销
                        tvTextRoll.setItemOnClickListener(new ITextBannerItemClickListener() {
                            @Override
                            public void onItemClick(Object data, int position) {
                                GongGaoInfo gongGaoInfo = mGongGaoList.get(position);
                                if(gongGaoInfo != null){
                                    int id = gongGaoInfo.getId();
                                    Intent mDetailIntent = new Intent(getActivity(), ArticleDetailActivity.class);
                                    mDetailIntent.putExtra("id",id);
                                    startActivity(mDetailIntent);
                                }
                            }
                        });
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case 422:
                showToast(infoBean.getMsg());
                break;
            default:
                break;
        }
    }

    @Override
    public void onSiteArticle(AllInfoBean infoBean) {
        //空实现
    }


    class MyPagerAdapter extends FragmentPagerAdapter {
        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return "";
        }

        @Override
        public Fragment getItem(int position) {
            if (position == 0) {
                //资讯
                return HomeTabFragment.newInstance("1");
            } else {
                //常见问题
                return HomeTabFragment.newInstance("2");
            }
        }

        @Override
        public int getCount() {
            return 2;
        }
    }


}
